require 'yaml'	
require 'permissions'
require 'evolution'
require 'jabber4r/rpc'
require 'thread'

class CalendarJabberBot
include Authorizer

	attr_reader :configuration,:permissions
	attr_accessor :config_file
	
  
	INTERFACE = XMLRPC::interface("") {
	      meth "string get_calendar(string)" 
	}


	def initialize(file)
		@config_file=file
	end

        def configure()
		@conf = YAML.load_file(@config_file)          
		jid = @conf['auth']['jid']+"/edsbotsrv"
		passwd = @conf['auth']['passwd']
		@permissions = @conf['permissions']		
		@reconfigured = (@server != nil)
		puts "Serving as #{jid}"
		@server = Jabber::RPC::BasicServer.new(jid, passwd)
		@server.add_handler( CalendarJabberBot::INTERFACE, self)
	end

	def get_calendar(usr, cal_uid)		
		puts "Trying to get calendar"
		cal_src = Evolution::get_esource_groups.collect{ |group|
				group.find{ |src| src.uid==cal_uid
			}
		}.compact.uniq
		return nil if cal_src == [] 			
		cal = Evolution::ECal.new(cal_src[0])
		str = cal.to_s()
		return str
    end

	def unauthorized_handler
		puts "trying to access unauthorized handler!!"
	end
	
	def run ()
		shutdown = false
		trap("INT") { 
		    shutdown = true
			puts "Ending..."
		}

		trap("HUP") {
			@server.shutdown
			@server = nil
			configure()
			@server.serve
		}
		self.configure()
		@server.serve
		while not shutdown do
		    sleep(1)
		end
                
		@server.shutdown
	end
		
	

	#This will make sure the client has read
	#access to our calendar
	check_read :get_calendar


end


if __FILE__ == $0 then
	srv=CalendarJabberBot.new(ENV["HOME"]+"/.edsbotrc")	
	puts "#{Process.pid}"
	srv.run()				
end  
